﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Facebook;
using System.IO.IsolatedStorage;
using EnglishStudy.Entity;
using System.Text;

namespace EnglishStudy.View
{
    public partial class Facebook : PhoneApplicationPage
    {
        public Facebook()
        {
            InitializeComponent();
            Loaded += Facebook_Loaded;
        }

        private FacebookClient asyncFbClient;
        private const string appID = "140232072849770";
        private const string appSecret = "7cd963f54280fe70982761952d2cff2e";

        void Facebook_Loaded(object sender, RoutedEventArgs e)
        {
            string[] extendedPermissions = new[] { "user_about_me", "publish_stream" };

            var oauth = new FacebookOAuthClient { AppId = appID, AppSecret = appSecret };
            var parameters = new Dictionary<string, object>
                            {
                                {"response_type", "token"},
                                {"display", "touch"}                                        
                            };
            if (extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                parameters["scope"] = scope.ToString();
            }

            var loginUrl = oauth.GetLoginUrl(parameters);
            webBrowser1.ClearCookiesAsync();
            webBrowser1.Navigated += CheckForAuth;
            webBrowser1.Navigate(loginUrl);
            webBrowser1.Visibility = Visibility.Visible;
        }

        private void CheckForAuth(object sender, NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(e.Uri, out result))
            {
                if (result.IsSuccess)
                {
                    
                    webBrowser1.Visibility = Visibility.Collapsed;
                    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
                    if (settings.Contains("MyFacebookAccessToken"))
                        settings["MyFacebookAccessToken"] = result.AccessToken;
                    else
                        settings.Add("MyFacebookAccessToken", result.AccessToken);
                    settings.Save();
                    asyncFbClient = new FacebookClient(result.AccessToken);
                    asyncFbClient.GetCompleted += asyncFbClient_GetCompleted;
                    asyncFbClient.GetAsync("/me");
                }
                else
                {
                    webBrowser1.Visibility = Visibility.Visible;
                }
            }
        }

        void asyncFbClient_GetCompleted(object sender, FacebookApiEventArgs e)
        {
            FacebookUser fbUser = e.GetResultData<FacebookUser>();
            PhoneApplicationService.Current.State["UserFacebook"] = fbUser;
            Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri(string.Format("/MainPage.Xaml"), UriKind.Relative)));
            asyncFbClient.GetCompleted -= asyncFbClient_GetCompleted;
        }

    }
}